package sz.szsmk.citizencard.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.layout.DefaultLayoutHelper;
import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.WeatherViewBinding;
import sz.szsmk.citizencard.model.network.bean.response.HomeHeadFuncResponse;
import sz.szsmk.citizencard.model.network.bean.response.HomeWeathRes;
import sz.szsmk.citizencard.model.network.bean.response.OneWordRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardResponse;
import sz.szsmk.citizencard.ui.activity.IMainActivity;
import sz.szsmk.citizencard.ui.activity.RoutineCardDetailActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/6/9 11:54
 * description:首页天气适配器
 */
public class WeatherAdapter extends DelegateAdapter.Adapter<WeatherAdapter.WeatherViewHolder> {

    private Context mContext;
    private LayoutHelper mDefaultLayoutHelper;
    private List<QueryUserCardResponse.DataBean> mData;
    private List<View> viewList;

    private HomeAddCardInferface homeAddCardInferface;


    private View view;
    private ArrayList<QueryUserCardResponse.DataBean> cardInfo;
    private ArrayList<QueryUserCardResponse.DataBean> mCardInfo;
    private ArrayList<ArrayList<QueryUserCardResponse.DataBean>> mendList;
    private ArrayList<ArrayList<QueryUserCardResponse.DataBean>> mNewsList;
    private LinearLayout weathLL;
    private OneWordRes oneWordData;
    private HomeWeathRes homeWeath;

    private List<HomeHeadFuncResponse.FunctionListBean> functionListBeanList;

    private CardAdapter vpAdapter;

    private View backView;

    private WeatherViewHolder holder;

    private int currentPosition = 0;
    private String flash;

    public WeatherAdapter(Context context, DefaultLayoutHelper weatherHelper, View backView) {
        mContext = context;
        mDefaultLayoutHelper = weatherHelper;
        this.backView = backView;
    }

    public void setOneWordData(OneWordRes oneWordData) {
        this.oneWordData = oneWordData;
    }

    public void setHomeWeath(HomeWeathRes homeWeath) {
        if (homeWeath != null) {
            this.homeWeath = homeWeath;
            notifyDataSetChanged();
        }
    }

    public void setFlash(String flash) {
        this.flash = flash;
    }


    public interface HomeAddCardInferface {
        public void onClick(View view, int position);
    }

    public void addCardOnClick(HomeAddCardInferface mdelArrressInterface) {
        homeAddCardInferface = mdelArrressInterface;
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return mDefaultLayoutHelper;
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    @Override
    public WeatherViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return WeatherViewHolder.creat(parent, backView);
    }

    @Override
    public int getItemViewType(int position) {
        return R.layout.weather_view;
    }

    @Override
    public void onBindViewHolder(WeatherViewHolder holder, int position) {
        this.holder = holder;
        loadItemData(position, holder.binding);
    }

    /**
     * 设置卡片第一张
     *
     * @param theFirst
     */
    public void setFirstCard(int theFirst) {
//        L.e(Constant.TAG, "卡片数量" + mCardInfo.size());
        if (mCardInfo != null) {

            if (mCardInfo.size() > theFirst) {
                holder.binding.homeCardVp.setCurrentItem(theFirst, true);
            }
        }
    }

    private void loadItemData(final int position, WeatherViewBinding binding) {
        final String access_token = ACache.get(mContext).getAsString("access_token");

        if (oneWordData != null) {
            String word = oneWordData.getWord();
            if (word.contains("|")) {
                String[] splitAddress = word.split("\\|");
                String mWord = splitAddress[0] + "\n" + splitAddress[1];
                binding.homeHeadTv.setText(mWord);
                binding.homeHeadTv.setVisibility(View.GONE);
            } else {
                binding.homeHeadTv.setText(word);
                binding.homeHeadTv.setVisibility(View.GONE);
            }

            if (!TextUtils.isEmpty(oneWordData.getLink_url())) {
                binding.homeHeadTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String url = oneWordData.getLink_url();
                        Bundle bundle = new Bundle();
                        bundle.putString("url", url);
                        bundle.putString(Constant.TITLE, "广告");
                        JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
                    }
                });
            } else
                binding.homeHeadTv.setOnClickListener(null);


        }
        if (homeWeath != null) {
            holder.binding.homeWheathLl.setVisibility(View.VISIBLE);
            binding.homeWheath.setText("市民卡");
            binding.homeWeath.setText("");
            binding.weathQuality.setText("");
            binding.homeKq.setText("");
        }
        weathLL = (LinearLayout) binding.getRoot().findViewById(R.id.home_wheath_ll);
        weathLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JumpUtils.jump(mContext, "weath", 0);
            }
        });

        binding.homeCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (access_token != null) {

                    Bundle bundle = new Bundle();
                    bundle.putString("key", "home");
                    JumpUtils.jumptoNatvie(mContext, "addnewcard", 0, bundle);
                } else {
                    toLogin();
                }
            }
        });

        if (functionListBeanList != null) {
            binding.card4.setVisibility(View.GONE);
            binding.card3.setVisibility(View.GONE);
            binding.card2.setVisibility(View.GONE);
            binding.card1.setVisibility(View.GONE);
            switch (functionListBeanList.size()) {
                case 4:
                    binding.card4.setVisibility(View.VISIBLE);
                    binding.headTitle4.setText(functionListBeanList.get(3).getFunction_name());
                    Glide.with(mContext)
                            .load(functionListBeanList.get(3).getIcon_url())
                            .into(binding.homeHeadIcon4);
                    binding.blurringView4.invalidateData();
                case 3:
                    binding.card3.setVisibility(View.VISIBLE);
                    binding.headTitle3.setText(functionListBeanList.get(2).getFunction_name());
                    Glide.with(mContext)
                            .load(functionListBeanList.get(2).getIcon_url())
                            .into(binding.homeHeadIcon3);
                    binding.blurringView3.invalidateData();
                case 2:
                    binding.card2.setVisibility(View.VISIBLE);
                    binding.headTitle2.setText(functionListBeanList.get(1).getFunction_name());
                    Glide.with(mContext)
                            .load(functionListBeanList.get(1).getIcon_url())
                            .into(binding.homeHeadIcon2);
                    binding.blurringView2.invalidateData();
                case 1:
                    binding.card1.setVisibility(View.VISIBLE);
                    binding.headTitle1.setText(functionListBeanList.get(0).getFunction_name());
                    Glide.with(mContext)
                            .load(functionListBeanList.get(0).getIcon_url())
                            .into(binding.homeHeadIcon1);
                    binding.blurringView1.invalidateData();
                    binding.homeApps.setVisibility(View.VISIBLE);
                    break;
                default:
                    binding.homeApps.setVisibility(View.GONE);
                    break;
            }
        }

        binding.blurringView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (homeAddCardInferface != null) {
                    homeAddCardInferface.onClick(view, 0);
                }
            }
        });

        binding.blurringView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (access_token == null) {
                    toLogin();
                } else {
                    ((IMainActivity) mContext).getmPresenter().recordUserFunction(102);
                    if (homeAddCardInferface != null) {
                        homeAddCardInferface.onClick(view, 1);
                    }
                }
            }
        });

        binding.blurringView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (homeAddCardInferface != null) {
                    homeAddCardInferface.onClick(view, 2);
                }
            }
        });

        binding.blurringView4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (access_token == null) {
                    toLogin();
                } else {
//                    使用IMainActivity的模板代码
                    ((IMainActivity) mContext).getmPresenter().recordUserFunction(104);
                    if (homeAddCardInferface != null) {
                        homeAddCardInferface.onClick(view, 3);
                    }
                }
            }
        });

        Log.i("zhong", "loadItemData: ==================================");
        if (mData != null && mData.size() == 0) {
            binding.homeCardVp.setVisibility(View.GONE);
            binding.blurringCard.setBlurredView(backView);
            binding.blurringCard.invalidateData();
//            binding.homeUncard.setVisibility(View.VISIBLE);
            binding.homeUncard.setVisibility(View.GONE);
            binding.homeUncard.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        } else if (mData != null && mData.size() > 0) {
            binding.homeCardVp.setVisibility(View.GONE);
            binding.homeUncard.setVisibility(View.GONE);
            ViewPager homeCardVp = binding.homeCardVp;
            homeCardVp.setPageMargin(40);
            homeCardVp.setOffscreenPageLimit(10);
            currentPosition = 0;
            vpAdapter = new CardAdapter(mContext, mNewsList, backView, false);
            vpAdapter.setPagerClickListener(new CardAdapter.PagerOnItemClickListener() {
                @Override
                public void onItemClick(int position, View view) {
                    Intent intent = new Intent(mContext, RoutineCardDetailActivity.class);
                    intent.setAction("action");
                    intent.putExtra("position", position);
                    mContext.startActivity(intent);
                }
            });
            homeCardVp.setAdapter(vpAdapter);
            homeCardVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    invalidateData(position);
                }

                @Override
                public void onPageSelected(int position) {
                    currentPosition = position;
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        } else {
            binding.homeCardVp.setVisibility(View.GONE);
//            binding.homeUncard.setVisibility(View.INVISIBLE);
            binding.homeUncard.setVisibility(View.GONE);
        }
    }


    public void toLogin() {
        JumpUtils.jump(mContext, "login", 0);
    }

    /**
     * 更新高斯模糊视图
     */
    public void invalidateData() {
        if (holder == null)
            return;

        if (holder.binding.card1.getVisibility() == View.VISIBLE)
            holder.binding.blurringView1.invalidateData();
        if (holder.binding.card2.getVisibility() == View.VISIBLE)
            holder.binding.blurringView2.invalidateData();
        if (holder.binding.card3.getVisibility() == View.VISIBLE)
            holder.binding.blurringView3.invalidateData();
        if (holder.binding.card4.getVisibility() == View.VISIBLE)
            holder.binding.blurringView4.invalidateData();

//        判断加载哪一个视图
        if (mData != null && mData.size() == 0)
            holder.binding.blurringCard.invalidateData();
        else
            invalidateData(currentPosition);
    }

    public void setFunctionListBeanList(List<HomeHeadFuncResponse.FunctionListBean> functionListBeanList) {
        this.functionListBeanList = functionListBeanList;
    }

    /**
     * 更新滚动卡片视图
     *
     * @param position
     */
    private void invalidateData(int position) {
        if (vpAdapter != null)
            vpAdapter.invalidateBlurView(position);
    }


    public void setCardData(List<QueryUserCardResponse.DataBean> data) {
        mData = data;
        if (data != null) {
            ArrayList<String> cardList = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {

                QueryUserCardResponse.DataBean dataBean = data.get(i);
                if (dataBean != null) {
                    String bindCardNo = dataBean.getBindCardNo();
                    cardList.add(bindCardNo);
                }
            }
            List<String> stringList = removeDuplicate(cardList);

            mNewsList = new ArrayList<>();
            for (int i = 0; i < stringList.size(); i++) {
                String card = stringList.get(i);
                mCardInfo = new ArrayList<>();
                mNewsList.add(mCardInfo);
                for (int j = 0; j < data.size(); j++) {
                    QueryUserCardResponse.DataBean dataBean = data.get(j);
                    String bindCardNo = data.get(j).getBindCardNo();
                    if (bindCardNo.equals(card)) {
                        mCardInfo.add(dataBean);
                    }
                }
            }
        }

    }

    public static List<String> removeDuplicate(ArrayList<String> titles)

    {
        Set set = new LinkedHashSet<String>();

        set.addAll(titles);
        titles.clear();
        titles.addAll(set);
        return titles;
    }

    static class WeatherViewHolder extends RecyclerView.ViewHolder {

        public WeatherViewBinding binding;

        public static WeatherViewHolder creat(ViewGroup parent, View backView) {
            WeatherViewBinding binding = WeatherViewBinding.inflate(LayoutInflater.from
                    ((parent.getContext())), parent, false);
            return new WeatherViewHolder(binding, backView);
        }

        public WeatherViewHolder(WeatherViewBinding binding, View backView) {
            super(binding.getRoot());
            this.binding = binding;
            binding.blurringView1.setBlurredView(backView);
            binding.blurringView2.setBlurredView(backView);
            binding.blurringView3.setBlurredView(backView);
            binding.blurringView4.setBlurredView(backView);
        }
    }

}
